﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace XinYi.CrookedShow.Core
{
    public class Reflet
    {
        public static List<T> DataTableToList<T>(DataTable dataTable)
        {
            //创建T集合
            List<T> list = new List<T>();
            //循环表格的行数
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                //创建一个实例
                T t = Activator.CreateInstance<T>();
                //获取T所有属性
                PropertyInfo[] propertyInfos = t.GetType().GetProperties();
                //循环每一列
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    foreach (PropertyInfo propertyInfo in propertyInfos)
                    {
                        //找到对应的属性
                        if (propertyInfo.Name.ToLower() == dataTable.Columns[j].ColumnName.ToLower())
                        {
                            if (dataTable.Rows[i][j] != DBNull.Value)
                            {
                                propertyInfo.SetValue(t, dataTable.Rows[i][j]);
                            }
                            else
                            {
                                propertyInfo.SetValue(t, null);
                            }
                        }
                    }
                }
                //加到集合里
                list.Add(t);
            }

            return list;
        }
    }
}
